﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.ComponentModel;

namespace RecordBeRun
{
    public class XMLHelper
    {
        public static BindingList<T> GetModelFromXmlFile<T>(string docRelativeUrl)
        {
            return GenericDeSerialize<T>(docRelativeUrl);
        }
        public static void SaveModelToXmlFile<T>(BindingList<T> list, string docRelativeUrl)
        {
            Serialize(list, docRelativeUrl);
        }
        //Deserialize
        public static BindingList<T> GenericDeSerialize<T>(string docRelativeUrl)
        {

            //Creating XmlSerializer for the object
            XmlSerializer serializer = new XmlSerializer(typeof(BindingList<T>));

            //Geting XMl from the file.
            TextReader tr = new StreamReader(docRelativeUrl);

            //Deserialize back to object from XML
            BindingList<T> b = (BindingList<T>)serializer.Deserialize(tr);
            tr.Close();
            return b;
        }
        //Generic serialize
        private static void Serialize<T>(BindingList<T> list, string docRelativeUrl)
        {
            //Creating XmlSerializer.
            XmlSerializer serializer = new XmlSerializer(typeof(BindingList<T>));
            //Creating text writer for xml data
            TextWriter tw = new StreamWriter(docRelativeUrl);
            //Convert the XML to List
            serializer.Serialize(tw, list);
            tw.Close();
        }
    }
}
